package com.tbit.main.controller;


import cn.hutool.core.collection.CollUtil;
import com.tbit.main.common.JsonResult;
import com.tbit.main.exception.BaseException;
import com.tbit.main.pojo.*;
import com.tbit.main.service.*;
import com.tbit.main.util.Assert;
import com.tbit.main.util.DateTimeUtil;
import com.tbit.main.util.OrderUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
import java.util.List;

/**
 * 运维举报
 *
 * @author Leon
 * 2020年3月11日 下午8:55:32
 */
@Validated
@RestController
@RequestMapping("/violationLog")
public class ViolationLogController {
    @Autowired
    private ViolationLogService violationLogService;
    @Autowired
    private MachineService machineService;
    @Autowired
    private AccountUserService accountUserService;
    @Autowired
    private RideLogService rideLogService;
    @Autowired
    private UserService userService;
    @Autowired
    private TokenService tokenService;
    @Autowired
    private AccountService accountService;
    @Autowired
    private GeoreMachineService georeMachineService;
    @Autowired
    private GeoreGionService georeGionService;


    /**
     * 查询
     */
    @RequestMapping("/query")
    public JsonResult getByTime(String token, Integer accountId, Integer violationState, String userPhone, String startTime, String endTime,
                                @RequestParam(value = "regionId", required = false) List<Integer> regionId) {
        AccountUser accountUserToken = tokenService.getAccount(token);

        Assert.hasLength(startTime, "System.startTime.notNull");
        Assert.hasLength(endTime, "System.endTime.notNull");
        Assert.notNull(accountId, "AccountUser.agentId.notNull");

        if (CollUtil.isEmpty(regionId)) {
            regionId = georeGionService.getByAccountUserId(accountUserToken.getAccountUserId());
        }

        List<ViolationLog> violationLogs = violationLogService.query(accountId, userPhone, violationState, startTime, endTime, regionId);

        return JsonResult.succ(violationLogs);
    }


    /**
     * 添加
     */
    @RequestMapping("/add")
    public JsonResult add(String token, Integer accountId, String userCode, Integer violationType, Double lon, Double lat, String imageIds, String reportDesc) {
        AccountUser accountUserToken = tokenService.getAccount(token);

        Assert.hasLength(userCode, "Machine.userCode.notNull");
        Assert.notNull(lon, "System.lon.notNull");
        Assert.notNull(lat, "System.lat.notNull");
        Assert.notNull(accountId, "AccountUser.agentId.notNull");
        if (violationType == null) {
            violationType = 0;
        }
        if (imageIds == null) {
            imageIds = "";
        }
        if (reportDesc == null) {
            reportDesc = "";
        }

        /**查询设备信息*/
        Machine machine = machineService.getByUseCode(userCode);
        if (machine == null) {
            throw new BaseException("Machine.notExist");
        }
        /**查询用户信息*/
        AccountUser accountUser = accountUserService.getById(accountUserToken.getAccountUserId());


        /**设备权限判断*/
        machineService.auth(accountUserToken.getAgents(), machine.getMachineId());
        /**查询最后一个借车用户*/
        RideLog rideLog = rideLogService.findLastByMachineId(machine.getMachineId());
        if (rideLog == null) {
            throw new BaseException("RideLog.notExist");
        }

        User user = userService.getByUserId(rideLog.getUserId());

        /**判断品牌下是否存在这辆车*/
        Integer machineAccount = accountService.getByAccount(machine.getAccountId());
        Integer accountUserAccount = accountService.getByAccount(accountId);
        if (!machineAccount.equals(accountUserAccount)) {
            throw new BaseException("Machine.notExist");
        }

        ViolationLog violationLog = new ViolationLog();
        violationLog.setAccountId(machine.getAccountId());
        violationLog.setWorkOrderNO(OrderUtil.getOrderNO());
        violationLog.setViolationType(violationType);
        violationLog.setMachineId(machine.getMachineId());
        violationLog.setMachineNO(machine.getMachineNO());
        violationLog.setUserCode(machine.getUserCode());
        violationLog.setUserId(user.getUserId());
        violationLog.setUserPhone(user.getPhone());
        violationLog.setUserName(user.getName() == null ? "" : user.getName());
        violationLog.setReportUserId(accountUser.getAccountUserId());
        violationLog.setReportUserName(accountUser.getName());
        violationLog.setReportPosition(lon + "," + lat);
        violationLog.setReportTime(DateTimeUtil.getNowTime());
        violationLog.setReportImageIds(imageIds);
        violationLog.setReportDesc(reportDesc);

        /**
         * 判断分区
         */
        GeoreMachine georeMachine = georeMachineService.getByMachineId(machine.getMachineId());
        if (georeMachine != null) {
            violationLog.setRegionId(georeMachine.getRegionId());
        }

        violationLogService.insert(violationLog);

        return JsonResult.succ();
    }

    /**
     * 处理 5.1.0版本弃用
     */
    @RequestMapping("/handle")
    public JsonResult handle(String token, Integer violationLogId, String handleResult, String handleDesc) {
        AccountUser accountUserToken = tokenService.getAccount(token);

        Assert.notNull(violationLogId, "System.id.notNull");
        Assert.hasLength(handleResult, "Violation.handleResult.notNull");

        if (handleDesc == null) {
            handleDesc = "";
        }

        /**查询用户信息*/
        AccountUser accountUser = accountUserService.getById(accountUserToken.getAccountUserId());

        ViolationLog violationLog = new ViolationLog();
        violationLog.setViolationLogId(violationLogId);
        violationLog.setViolationState(1);
        violationLog.setHandleUserId(accountUser.getAccountUserId());
        violationLog.setHandleTime(DateTimeUtil.getNowTime());
        violationLog.setHandleResult(handleResult);
        violationLog.setHandleUserName(accountUser.getName());
        violationLog.setHandleDesc(handleDesc);

        violationLogService.handle(violationLog);

        return JsonResult.succ();
    }

    /**
     * 处理举报记录
     *
     * @param token          token
     * @param violationLogId 举报记录id
     * @param handleResult   处理结果 0:驳回 1:通过
     * @param handleDesc     处理内容 如果是通过并回复,这里填回复内容。如果是驳回，这里填驳回原因
     * @param type           1:小程序回复用户 2:拉黑用户
     * @param blockTime      拉黑时间(字符串时间 年-月-日)
     * @param photosUrl      拉黑照片 上传的照片的url，多个使用,隔开
     */
    @RequestMapping("/handleNew")
    public JsonResult handleNew(String token, @NotNull Integer violationLogId, @NotNull Integer handleResult,
                                @Size(max = 200, message = "回复内容限制0-200汉字") String handleDesc, Integer type,
                                String blockTime, String photosUrl) {
        AccountUser accountUserToken = tokenService.getAccount(token);

        if (handleDesc == null) {
            handleDesc = "";
        }
        /**查询用户信息*/
        AccountUser accountUser = accountUserService.getById(accountUserToken.getAccountUserId());

        violationLogService.handleNew(accountUser, violationLogId, handleResult, handleDesc, type, blockTime, photosUrl);

        return JsonResult.succ();
    }


    /**
     * 根据id查询
     */
    @RequestMapping("/getById")
    public JsonResult getById(String token, Integer violationLogId) {
        Assert.notNull(violationLogId, "System.id.notNull");

        ViolationLog violationLog = violationLogService.getById(violationLogId);

        return JsonResult.succ(violationLog);
    }

}